<template>
  <el-dialog :title="title" v-model="drawer" width="700px" :append-to-body="true" @close="close">
    <el-form size="small" :model="form" :rules="rules" label-width="120px" ref="ruleRefForm">
	   	<el-form-item label="优惠卷名称" prop="couponName">
	   		<el-input v-model="form.couponName" placeholder="请输入优惠卷名称"></el-input>
	   	</el-form-item>
	   	<el-form-item label="优惠卷类型" prop="couponType">
	   		<el-select v-model="form.couponType" placeholder="请选择优惠卷类型" class="w100">
	   			<el-option v-for="item in couponTypeOptions" :key="item.value" :label="item.label"
	   				:value="item.value"> </el-option>
	   		</el-select>
	   	</el-form-item>
	   	<el-form-item label="使用方式" prop="useType">
	   		<el-radio-group v-model="form.useType">
	   			<el-radio v-for="(item,index) in useTypeOptions" :label="item.value" :key="index">{{item.label}}
	   			</el-radio>
	   		</el-radio-group>
	   	</el-form-item>
	   	<el-form-item label="请选择分类"  v-if="form.useType == 1">
			<el-cascader :options="classify" :show-all-levels="false" v-model="form.catalogId"
				:props="{value: 'id', label: 'name'}"></el-cascader>
	   </el-form-item>
	   <el-form-item label="请关联商品"  v-if="form.useType == 2">
		   <el-tag class="spec-tag" v-for="(item, index) in form.smsCouponSpuRelations" :key="item.spuId" closable
		   	size="small" style="margin-right:10px;height: 25px;" effect="light"
		   	@close="delSpu(index)">{{item.spuName}}</el-tag>
			<el-button type="primary" @click="selectShopList">关联商品</el-button>
	   </el-form-item>
	   	<el-form-item label="发布状态">
	   		<el-radio-group v-model="form.publishStatus">
	   			<el-radio v-for="(item,index) in publishStatusOptions" :label="item.value" :key="index">{{item.label}}
	   			</el-radio>
	   		</el-radio-group>
	   	</el-form-item>
		   <el-form-item label="发行数量" prop="publishCount">
	   		<el-input-number v-model="form.publishCount" controls-position="right" :min="form.num" :step="1">
	   		</el-input-number>
	   	</el-form-item>
	   	<el-form-item label="数量" prop="num">
	   		<el-input-number v-model="form.num" controls-position="right" :min="1" :step="1">
	   		</el-input-number>
	   	</el-form-item>
	   	<el-form-item label="优惠方式" prop="preferentialWay">
	   		<el-radio-group v-model="form.preferentialWay"  @change="selectPreferentialWay">
	   			<el-radio v-for="(item,index) in preferentialWayOptions" :label="item.value" :key="index">{{item.label}}
	   			</el-radio>
	   		</el-radio-group>
	   	</el-form-item>
	   	<el-form-item prop="amount">
	   		<el-row>
	   			<el-input-number v-model="form.amount" controls-position="right" :min="0" :step="0.01">
	   			</el-input-number>
	   		</el-row>
	   		<span
	   			style="color: red;">{{form.preferentialWay === 0 ? '请输入优惠金额' :'请输入优惠折扣（0和1不为折扣，例如：0.95为9.5折）'}}
	   		</span>
	   	</el-form-item>
	   	<el-form-item label="限领张数" prop="perLimit">
	   		<el-input-number v-model="form.perLimit" controls-position="right" :min="0" :step="1">
	   		</el-input-number>
	   	</el-form-item>
	   	<el-form-item label="最低消费金额" prop="minPoint">
	   		<el-input-number v-model="form.minPoint" controls-position="right" :min="0" :step="1">
	   		</el-input-number>
	   	</el-form-item>	   	
	   	<el-form-item label="使用时间" prop="useTimeType">
	   		<el-radio-group v-model="form.useTimeType" >
	   			<el-radio v-for="(item,index) in useTimeTypeOptions" :label="item.value" :key="index">{{item.label}}
	   			</el-radio>
	   		</el-radio-group>
	   	</el-form-item>
	   	<el-form-item  v-if="form.useTimeType === 0">
	   		<el-row>
	   			<el-input-number v-model="form.usePointDay" controls-position="right" :min="1" :step="1">
	   			</el-input-number>
	   		</el-row>
	   		<span style="color: red;">领取后多少天内使用</span>
	   	</el-form-item>
	   	<el-form-item prop="startTime" v-if="form.useTimeType === 1">
	   		<el-date-picker v-model="form.startTime" type="datetime" :value-format="valueFormat"
	   			placeholder="选择开始使用时间">
	   		</el-date-picker>
	   		至
	   		<el-date-picker v-model="form.endTime" type="datetime" :value-format="valueFormat"
	   			placeholder="选择结束时间">
	   		</el-date-picker>
	   	</el-form-item>
	   	
	   	<el-form-item label="领取时间" prop="receiveTimeType" >
	   		<el-radio-group v-model="form.receiveTimeType" >
	   			<el-radio v-for="(item,index) in receiveTimeTypeOptions" :label="item.value" :key="index">{{item.label}}
	   			</el-radio>
	   		</el-radio-group>
	   	</el-form-item>
	   	<el-form-item v-if="form.receiveTimeType === 0">
	   		<el-date-picker v-model="form.enableStartTime" type="datetime" :value-format="valueFormat"
	   			placeholder="选择领取时间时间">
	   		</el-date-picker>
	   		至
	   		<el-date-picker v-model="form.enableEndTime" type="datetime" :value-format="valueFormat"
	   			placeholder="选择领取结束时间">
	   		</el-date-picker>
	   	</el-form-item>
	   
	   	<el-form-item label="备注">
	   		<el-input type="textarea" v-model="form.note"></el-input>
	   	</el-form-item>
	   
        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleRefForm)" size="small">提交</el-button>
			<el-button @click="resetForm(ruleRefForm)" size="small">取消</el-button>
        </el-form-item>
    </el-form>
  </el-dialog>
  
  <select-shop v-model:dialogDrawer="dialogShopVisible" title="关联商品" :is-batch="true"
  	@onSelectSubmit="selectShopSubmit" ></select-shop>
  
  
  
  
</template>

<script>
import { computed, reactive, toRefs,ref } from 'vue'
import { ElMessage } from 'element-plus'
import { create,update } from '/@/api/sms/coupon'
import SelectShop from './SelectShop.vue'
import api from '/@/api/commonApi'

export default {
    name: 'CouponDetail',
    props: {
        dialogDrawer: {
            type: Boolean,
            default: false
        },
        title: {
            type: String,
            default: '新增规格'
        },
        defaultForm: {
            type: Object,
            default() {
                return {}
            }
        },
        couponTypeOptions: {
            type: Array,
            default() {
                return []
            }
        },
		useTypeOptions: {
		    type: Array,
		    default() {
		        return []
		    }
		},
		publishStatusOptions: {
		    type: Array,
		    default() {
		        return []
		    }
		},
		preferentialWayOptions: {
		    type: Array,
		    default() {
		        return []
		    }
		},
		receiveTimeTypeOptions: {
		    type: Array,
		    default() {
		        return []
		    }
		},
		useTimeTypeOptions: {
		    type: Array,
		    default() {
		        return []
		    }
		},
		classify: {
		    type: Array,
		    default() {
		        return []
		    }
		},
    },
	components: {
		SelectShop
	},
    setup(props, context) {
        const { dialogDrawer, defaultForm } = toRefs(props)
		 const ruleRefForm = ref()
        const drawer = computed({
            get: () => dialogDrawer.value,
            set: val => {
                context.emit('update:dialogDrawer', val)
            }
        })
        let form = computed({
            get: () => defaultForm.value,
            set: val => {
               context.emit('update:defaultForm', val) 
            }
        })
        const state = reactive({
            rules: {
               couponName: [{
               	required: true,
               	message: '请输入优惠卷名称',
               	trigger: 'blur'
               }],
               couponType: [{
               	required: true,
               	message: '请选择优惠卷类型',
               	trigger: 'blur'
               }],
               receiveTimeType: [{
               	required: true,
               	message: '请选择领取时间',
               	trigger: 'blur'
               }],
               useTimeType: [{
               	required: true,
               	message: '请选择使用时间',
               	trigger: 'blur'
               }],
            },
            specItem: '',
			isAddSpecValue:false,
			valueFormat: 'YYYY-MM-DD HH:mm:ss',
			dialogShopVisible:false,
			smsCouponSpuRelations:[]
        })
        const close = () => {
            context.emit('update:dialogDrawer', false)
        }
        const submitForm = async (formEl) => {
            if (!formEl) return
            await formEl.validate((valid) => {
                if (valid) {
					let data = form.value
					// data.smsCouponSpuRelations = state.smsCouponSpuRelations
					// 修改
					if(data.catalogId && data.catalogId.length > 0){
						console.log("进入：" + String(data.catalogId[data.catalogId.length - 1]));
						data.catalogId = String(data.catalogId[data.catalogId.length - 1])
					}
					if(data.id!=null && data.id!= ''){
					 update(data).then(res=>{
						 if(res.code == 0){
							ElMessage.success("修改成功");
							context.emit('onDetailSubmit', true)
						 }else{
							ElMessage.error("修改失败");
						 }
					 })
					 
					}
					// 新增
					else{
						create(data).then(res=>{
							if(res.code == 0){
							 ElMessage.success("添加成功");
							 context.emit('onDetailSubmit', true)
							}else{
							 ElMessage.error("添加失败");
							}
						})
						 
					}
                }
            })
        }
        const resetForm = (formEl) => {
            if (!formEl) return
            context.emit('update:dialogDrawer', false)
            formEl.resetFields()
        }
		// 关联商品
		const selectShopList = () => {
		   state.dialogShopVisible = true
		}
		const selectShopSubmit = (data) => {
			let v = []
			for(let d of data){
				v.push({spuId:d.id,spuName:d.spuName})
			}
			state.dialogShopVisible = false
			form.value.smsCouponSpuRelations = v
		}
		//移除商品
		const delSpu = (index) => {
		   form.value.smsCouponSpuRelations.splice(index, 1)
		}
		const selectPreferentialWay = (val) => {
			form.value.amount = 0
		}
		
		
        return {
            drawer,
            form,
            close,
            submitForm,
            resetForm,
			ruleRefForm,
			selectShopList,
			selectShopSubmit,
			delSpu,
			selectPreferentialWay,
            ...toRefs(state)
        }
    }
}
</script>

<style>

</style>